﻿using HY.Common;
using HY.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HY.Web
{
    /// <summary>
    /// 权限验证
    /// </summary>
    public class AuthorizeAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            //是否跳过权限验证
            if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), false) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
                return;

            //用户是否登录或登录失效
            V_UserInfo userinfo = GlobalSupport.CurrentUser;
            if (userinfo == null)
            {
                filterContext.Result = new ContentResult() { Content = "<script type='text/javascript'>top.location.href='/Home/Login';</script>" };
                //filterContext.Result = new RedirectResult("/Home/Login");
                return;
            }
            //判断是否超级管理员
            if(userinfo.UserName != GlobalConfig.AdminUserName)
            {
                //获取区域名称
                var areaName = filterContext.RouteData.DataTokens["area"] == null ? null : filterContext.RouteData.DataTokens["area"].ToString();
                var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
                var actionName = filterContext.ActionDescriptor.ActionName;

                //权限验证
                if (!GlobalSupport.CheckAuthorize(areaName, controllerName, actionName))
                {
                    //ReturnData returnData = new ReturnData()
                    //{
                    //    Status = StatusCode.Error.ToString(),
                    //    Message = "没有操作权限！"
                    //};
                    //JsonResult json = new JsonResult();
                    //json.Data = returnData;
                    //json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    //filterContext.Result = json;
                }
            }
        }
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            //var msg = $"用户: {CurrentUserInfo?.UserName}, 链接: {Request.Url}";
            //if (Request.HttpMethod == "POST")
            //    msg += $", 数据: {HttpUtility.UrlDecode(Request.Form.ToString())}";
            //Log.Debug(msg);
        }
    }
}